#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <string>
#include <unistd.h>
#include <fcntl.h>

#define PATH "./"
#define FILENAME "myfifo"

#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

/* 创建pipe(FIFO文件) */
class CreateFIFO
{
public:
    void OpenForRead()
    {
        _fd = open(_pathname.c_str(), O_RDONLY);
        if (_fd < 0)
            ERR_EXIT("open_for_read fail");
        else
            std::cout << "open_for_read success!" << std::endl;
    }

    void OpenForWrite()
    {
        _fd = open(_pathname.c_str(), O_WRONLY);
        if (_fd < 0)
            ERR_EXIT("open_for_write fail");
        else
            std::cout << "open_for_write success!" << std::endl;
    }

    void Write()
    {
        int cnt = 1;
        pid_t id = getpid();
        while (true)
        {
            std::cout << "Please Enter#" << std::endl;
            std::getline(std::cin, _message);
            _message += (", message number: " + std::to_string(cnt++) + ", [" + std::to_string(id) + "]");
            write(_fd, _message.c_str(), _message.size());
        }
    }

    void Read()
    {
        while (true)
        {
            char buffer[1024];
            int n = read(_fd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << "Client Say# " << buffer << std::endl;
            }
            else if (n == 0)
            {
                std::cout << "Client quit! me too!" << std::endl;
                break;
            }
            else
            {
                ERR_EXIT("read fail");
                break;
            }
        }
    }

    CreateFIFO(const std::string &path, const std::string &name, const mode_t &mode = 0666)
        : _mode(mode), _fd(-1)
    {
        _pathname = PATH + name;
    }

    void Create()
    {
        /* 创建FIFO文件 */
        umask(0);
        int n = mkfifo(_pathname.c_str(), _mode);
        if (n < 0)
            ERR_EXIT("mkfifo fail");
        else
            std::cout << "mkfifo success!" << std::endl;
    }

    void Close()
    {
        if (_fd > 0)
        {
            int m = close(_fd);
            if (m < 0)
                ERR_EXIT("Close fail");
            else
                std::cout << "Close success!" << std::endl;
        }
    }

    ~CreateFIFO()
    {
        int n = unlink(_pathname.c_str());
        if (n < 0)
            ERR_EXIT("unlink fail");
        else
            std::cout << "unlink success!" << std::endl;
    }

private:
    std::string _pathname;
    mode_t _mode;
    int _fd;
    std::string _message;
};
